
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>内置视图 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="元文件和杂记" href="../misc/index.html" />
    <link rel="prev" title="验证器" href="validators.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="validators.html" title="验证器">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="../misc/index.html" title="元文件和杂记">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-views">
            
  <div class="section" id="s-module-django.views">
<span id="s-built-in-views"></span><span id="module-django.views"></span><span id="built-in-views"></span><h1>内置视图<a class="headerlink" href="#module-django.views" title="永久链接至标题">¶</a></h1>
<p>Django 内置的几个视图在 <a class="reference internal" href="../topics/http/views.html"><span class="doc">编写视图</span></a> 以及文档的其他地方都有记载。</p>
<div class="section" id="s-serving-files-in-development">
<span id="serving-files-in-development"></span><h2>为开发中的文件提供服务<a class="headerlink" href="#serving-files-in-development" title="永久链接至标题">¶</a></h2>
<dl class="function">
<dt id="django.views.static.serve">
<code class="descclassname">static.</code><code class="descname">serve</code>(<em>request</em>, <em>path</em>, <em>document_root</em>, <em>show_indexes=False</em>)<a class="headerlink" href="#django.views.static.serve" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>除了你的项目的静态资源外，可能还有一些其他的文件，为了方便，你想让 Django 在本地开发中为你提供服务。<a class="reference internal" href="#django.views.static.serve" title="django.views.static.serve"><code class="xref py py-func docutils literal notranslate"><span class="pre">serve()</span></code></a> 视图可以用来为你给它的任何目录提供服务。（这个视图并 <strong>没有</strong> 强到用于生产，只应该作为开发辅助工具，你应该在生产中使用真正的前端 Web 服务器来服务这些文件）。</p>
<p>最有可能的例子是用户在 <a class="reference internal" href="settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 中上传的内容。<code class="docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code> 是为静态资源设计的，并没有内置处理用户上传文件的功能，但是你可以通过在 URLconf 中添加这样的内容，让 Django 为你的 <a class="reference internal" href="settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 服务：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">re_path</span>
<span class="kn">from</span> <span class="nn">django.views.static</span> <span class="kn">import</span> <span class="n">serve</span>

<span class="c1"># ... the rest of your URLconf goes here ...</span>

<span class="k">if</span> <span class="n">settings</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">:</span>
    <span class="n">urlpatterns</span> <span class="o">+=</span> <span class="p">[</span>
        <span class="n">re_path</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^media/(?P&lt;path&gt;.*)$&#39;</span><span class="p">,</span> <span class="n">serve</span><span class="p">,</span> <span class="p">{</span>
            <span class="s1">&#39;document_root&#39;</span><span class="p">:</span> <span class="n">settings</span><span class="o">.</span><span class="n">MEDIA_ROOT</span><span class="p">,</span>
        <span class="p">}),</span>
    <span class="p">]</span>
</pre></div>
</div>
<p>注意，这段代码假设你的 <a class="reference internal" href="settings.html#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> 的值是 <code class="docutils literal notranslate"><span class="pre">'/media/'</span></code>。这将调用 <code class="xref py py-func docutils literal notranslate"><span class="pre">service()</span></code> 视图，传递 URLconf 的路径和（必要的）``document_root`` 参数。</p>
<p>由于定义这种 URL 模式可能会变得有点麻烦，Django 提供了一个小的 URL 辅助函数 <a class="reference internal" href="urls.html#django.conf.urls.static.static" title="django.conf.urls.static.static"><code class="xref py py-func docutils literal notranslate"><span class="pre">static()</span></code></a>，它的参数是前缀，如 <a class="reference internal" href="settings.html#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> 和一个指向视图的点分隔路径，如 <code class="docutils literal notranslate"><span class="pre">'django.views.static.service'</span></code>。其他任何函数参数都将透明地传递给视图。</p>
</div>
<div class="section" id="s-error-views">
<span id="s-id1"></span><span id="error-views"></span><span id="id1"></span><h2>错误视图<a class="headerlink" href="#error-views" title="永久链接至标题">¶</a></h2>
<p>Django 默认提供了一些处理 HTTP 错误的视图。要用你自己的自定义视图覆盖这些视图，请参见 <a class="reference internal" href="../topics/http/views.html#customizing-error-views"><span class="std std-ref">自定义报错视图</span></a>。</p>
<div class="section" id="s-the-404-page-not-found-view">
<span id="s-http-not-found-view"></span><span id="the-404-page-not-found-view"></span><span id="http-not-found-view"></span><h3>404（页面没有找到)）视图<a class="headerlink" href="#the-404-page-not-found-view" title="永久链接至标题">¶</a></h3>
<dl class="function">
<dt id="django.views.defaults.page_not_found">
<code class="descclassname">defaults.</code><code class="descname">page_not_found</code>(<em>request</em>, <em>exception</em>, <em>template_name='404.html'</em>)<a class="headerlink" href="#django.views.defaults.page_not_found" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>当你在视图中提出 <a class="reference internal" href="../topics/http/views.html#django.http.Http404" title="django.http.Http404"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Http404</span></code></a> 时，Django 会加载一个专门处理 404 错误的视图。默认情况下，它是视图 <a class="reference internal" href="#django.views.defaults.page_not_found" title="django.views.defaults.page_not_found"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.views.defaults.page_not_found()</span></code></a>，如果你在根模板目录下创建了模板 <cite>404.html`</cite>，那么它要么产生“Not Found”消息，要么加载并渲染它。</p>
<p>默认的 404 视图将向模板传递两个变量：<code class="docutils literal notranslate"><span class="pre">request_path</span></code>，这是导致错误的 URL，和 <code class="docutils literal notranslate"><span class="pre">exception</span></code>，这是触发视图的异常的有用表示（例如，包含传递给特定 <code class="docutils literal notranslate"><span class="pre">Http404</span></code> 实例的任何消息）。</p>
<p>关于 404 视图需要注意的三个要点：</p>
<ul class="simple">
<li>如果 Django 在检查了 URLconf 中的每一个正则表达式后都没有找到匹配的结果，也会调用 404 视图。</li>
<li>404 视图被传递了一个 <a class="reference internal" href="templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestContext</span></code></a>，并且将可以访问由你的模板上下文处理器提供的变量（例如 <code class="docutils literal notranslate"><span class="pre">MEDIA_URL</span></code>）。</li>
<li>如果 <a class="reference internal" href="settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code> （在你的配置模块中），那么你的 404 视图将永远不会被使用，而你的 URLconf 将被显示，并附带一些调试信息。</li>
</ul>
</div>
<div class="section" id="s-the-500-server-error-view">
<span id="s-http-internal-server-error-view"></span><span id="the-500-server-error-view"></span><span id="http-internal-server-error-view"></span><h3>500（服务器错误）视图<a class="headerlink" href="#the-500-server-error-view" title="永久链接至标题">¶</a></h3>
<dl class="function">
<dt id="django.views.defaults.server_error">
<code class="descclassname">defaults.</code><code class="descname">server_error</code>(<em>request</em>, <em>template_name='500.html'</em>)<a class="headerlink" href="#django.views.defaults.server_error" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>同样，在视图代码出现运行时错误的情况下，Django 也会执行特定行为。如果一个视图出现异常，Django 默认会调用视图 <code class="docutils literal notranslate"><span class="pre">django.views.defaults.server_error</span></code>，如果你在根模板目录下创建了模板 <code class="docutils literal notranslate"><span class="pre">500.html</span></code>，则会产生一个“Server Error”消息或加载并渲染模板 <code class="docutils literal notranslate"><span class="pre">500.html</span></code>。</p>
<p>默认的 500 视图不向 <code class="docutils literal notranslate"><span class="pre">500.html</span></code> 模板传递任何变量，并以一个空的 <code class="docutils literal notranslate"><span class="pre">Context</span></code> 呈现，以减少额外错误的机会。</p>
<p>如果 <a class="reference internal" href="settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG</span></code></a> 被设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code> （在你的配置模块中），那么你的 500 视图将永远不会被使用，而会显示一些调试信息的回溯。</p>
</div>
<div class="section" id="s-the-403-http-forbidden-view">
<span id="s-http-forbidden-view"></span><span id="the-403-http-forbidden-view"></span><span id="http-forbidden-view"></span><h3>403（HTTP 禁止）视图<a class="headerlink" href="#the-403-http-forbidden-view" title="永久链接至标题">¶</a></h3>
<dl class="function">
<dt id="django.views.defaults.permission_denied">
<code class="descclassname">defaults.</code><code class="descname">permission_denied</code>(<em>request</em>, <em>exception</em>, <em>template_name='403.html'</em>)<a class="headerlink" href="#django.views.defaults.permission_denied" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>与 404 和 500 视图一样，Django 也有一个视图来处理 403 禁止错误。如果一个视图出现 403 异常，那么 Django 默认会调用视图 <code class="docutils literal notranslate"><span class="pre">django.views.defaults.permission_denied</span></code>。</p>
<p>这个视图从你的根模板目录加载和渲染 <code class="docutils literal notranslate"><span class="pre">403.html</span></code> 模板，如果这个文件不存在将会显示“403 Forbidden”，按照 <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html#section-6.5.3"><strong>RFC 7231#section-6.5.3</strong></a> （HTTP 1.1 规范）。 模板上下文包含 <code class="docutils literal notranslate"><span class="pre">exception</span></code>，它是触发视图的异常的字符串表示形式。</p>
<p><code class="docutils literal notranslate"><span class="pre">django.views.defaults.permission_denied</span></code> 由一个 <a class="reference internal" href="exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a> 异常触发。要拒绝一个视图的访问，你可以使用这样的代码：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="kn">import</span> <span class="n">PermissionDenied</span>

<span class="k">def</span> <span class="nf">edit</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">pk</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_staff</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">PermissionDenied</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-400-bad-request-view">
<span id="s-http-bad-request-view"></span><span id="the-400-bad-request-view"></span><span id="http-bad-request-view"></span><h3>400（错误请求）视图<a class="headerlink" href="#the-400-bad-request-view" title="永久链接至标题">¶</a></h3>
<dl class="function">
<dt id="django.views.defaults.bad_request">
<code class="descclassname">defaults.</code><code class="descname">bad_request</code>(<em>request</em>, <em>exception</em>, <em>template_name='400.html'</em>)<a class="headerlink" href="#django.views.defaults.bad_request" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>当 Django 中发生了一个 <a class="reference internal" href="exceptions.html#django.core.exceptions.SuspiciousOperation" title="django.core.exceptions.SuspiciousOperation"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SuspiciousOperation</span></code></a> 时，可能会被 Django 的某个组件处理（比如重置会话数据）。如果没有特别处理，Django 会将当前请求视为“bad request”而不是服务器错误。</p>
<p><code class="docutils literal notranslate"><span class="pre">django.views.defaults.bad_request</span></code>，在其他方面与 <code class="docutils literal notranslate"><span class="pre">server_error</span></code> 视图非常相似，但返回的状态码为 400，表示错误条件是由客户端操作造成的。默认情况下，与触发该视图的异常无关的任何内容都不会传递给模板上下文，因为异常消息可能包含文件系统路径等敏感信息。</p>
<p><code class="docutils literal notranslate"><span class="pre">bad_request</span></code> 视图也只有在 <code class="xref std std-setting docutils literal notranslate"><span class="pre">DEBUG`</span></code> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时才能使用。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">内置视图</a><ul>
<li><a class="reference internal" href="#serving-files-in-development">为开发中的文件提供服务</a></li>
<li><a class="reference internal" href="#error-views">错误视图</a><ul>
<li><a class="reference internal" href="#the-404-page-not-found-view">404（页面没有找到)）视图</a></li>
<li><a class="reference internal" href="#the-500-server-error-view">500（服务器错误）视图</a></li>
<li><a class="reference internal" href="#the-403-http-forbidden-view">403（HTTP 禁止）视图</a></li>
<li><a class="reference internal" href="#the-400-bad-request-view">400（错误请求）视图</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="validators.html"
                        title="上一章">验证器</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="../misc/index.html"
                        title="下一章">元文件和杂记</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/ref/views.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="validators.html" title="验证器">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="../misc/index.html" title="元文件和杂记">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>